# coding:utf-8
"""下载器组件"""

import requests
import chardet

from ..http.response import Response


class Downloader(object):
    """根据请求对象(Request), 发起HTTP/HTTPS网络请求, 拿到HTTP/HTTPS响应, 构建响应对象(Response)并返回"""

    def send_request(self, request):
        """发起请求获取响应的方法"""
        # 判断请求方式, 发起对应请求
        if request.method.upper() == "GET":
            response = requests.get(url=request.url, headers=request.headers, params=request.params)
        elif request.method.upper() == "POST":
            response = requests.post(url=request.url, headers=request.headers, params=request.params,
                                     data=request.formdata)
        else:
            # 若不是指定请求方式,则抛出异常
            raise TypeError("[MethodError]: {} no the method : {}".format(request.url, request.method))
        # 构建响应对象, 并返回
        return Response(
            url=response.url,
            body=response.content,
            status_code=response.status_code,
            headers=response.headers,
            encoding=chardet.detect(response.content)["encoding"]
        )
